package com.hk.api.imagesearch;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hk.api.imagesearch.vo.ImageVO;
import com.hk.exception.BusinessException;
import com.hk.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author huangkun
 * @date 2025/1/11 19:20
 */
@Slf4j
public class ImageSearchApi {
    //获取图片页面地址
    private static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        try {
            // 2. 发送 POST 请求到百度接口
            HttpResponse response = HttpRequest.post(url).form(formData).timeout(5000).execute();
            // 判断响应状态
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "接口调用失败");
            }
            // 解析响应
            String responseBody = response.body();
            Map<String, Object> result = JSONUtil.toBean(responseBody, Map.class);

            // 3. 处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "接口调用失败");
            }
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            String rawUrl = (String) data.get("url");
            // 对 URL 进行解码
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            // 如果 URL 为空
            if (searchResultUrl == null) {
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "未返回有效结果");
            }
            return searchResultUrl;
        } catch (Exception e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "搜索失败");
        }
    }

    //获取图片列表地址
    private static String getImageFirstUrl(String pageUrl) {
        try {
            String firstUrl =null;
            //解析页面地址
            Document document = Jsoup.connect(pageUrl).get();
            Elements elements = document.getElementsByTag("script");
            for (Element element : elements) {
                //找到包含firstUrl的script标签
                String scriptContent = element.html();
                if (scriptContent.contains("firstUrl")) {
                    //提取firstUrl
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                         firstUrl = matcher.group(1);
                        // 处理转义字符
                        firstUrl = firstUrl.replace("\\/", "/");
                        log.error("firstUrl:{}", firstUrl);
                        break;
                    }
                }
            }
            return firstUrl;
        } catch (Exception e) {
            log.error("提取图片失败", e);
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "提取图片失败");
        }
    }

    //根据图片列表地址解析获取图片
    private static List<ImageVO> extractImages(String url) {
        try {
            HttpResponse response = HttpUtil.createGet(url).execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                String body = response.body();
                //解析body成JSON
                JSONObject jsonObject = new JSONObject(body);
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray jsonArray = data.getJSONArray("list");
                List<ImageVO> imageVOS = JSONUtil.toList(jsonArray, ImageVO.class);
                return imageVOS;
            } else {
                log.error("请求失败，状态码：{}", response.getStatus());
                throw new BusinessException(ErrorCode.ERROR_SYSTEM, "提取图片失败");
            }
        } catch (Exception e) {
            log.error("提取图片失败,错误信息：", e);
            throw new BusinessException(ErrorCode.ERROR_SYSTEM, "提取图片失败");
        }
    }

    /**
     * 根据图片地址获取相似图片列表地址
     * @param imageUrl 图片地址
     */
    public static List<ImageVO> searchImages(String imageUrl) {
        String pageUrl = getImagePageUrl(imageUrl);
        String imageFirstUrl = getImageFirstUrl(pageUrl);
        return extractImages(imageFirstUrl);
    }


    public static void main(String[] args) {
        String imageUrl = "https://hk-1333249985.cos.ap-guangzhou.myqcloud.com//1867174703740837890/20250110152256_fT3CP1AZd7gRjunO.png";
        List<ImageVO> imageVOS = searchImages(imageUrl);
        System.out.println(imageVOS);

    }
}
